//
//  LZTheHostCollectionViewCell.m
//  沙哈拉FM
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 S1mpl3. All rights reserved.
//

#import "LZTheHostCollectionViewCell.h"
#import "FitHeader.h"
#import "LZHostDetailControllerViewCell.h"
#import "HeadViewButton.h"
#import "TwoToOne.h"
#import "TheHost.h"
#import "S1mpl3HeadInfoViewController.h"
#import "MJRefresh.h"
#import "CoreDataManager.h"
#import "Dic.h"
#import "UIImage+GIF.h"

@interface LZTheHostCollectionViewCell ()
@property(nonatomic, strong)NSMutableArray *listArray;
@property(nonatomic, strong)CoreDataManager *manager;

@end

@implementation LZTheHostCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
      
        [self createView];
       
    }
    return self;
}
- (void)createView{
    _manager = [CoreDataManager shareManager];
    _dataArray = [NSMutableArray array];
    _array = [NSMutableArray array];
    _zhuBoArray = [NSMutableArray array];
    _listArray = [NSMutableArray array];
    
    _flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _flowLayout.itemSize = CGSizeMake(115 * FITWidth, 120 * FITHeight);
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.sectionInset = UIEdgeInsetsMake(0, 5 * FITWidth, 10 * FITHeight, 5 * FITWidth);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height) collectionViewLayout:_flowLayout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor colorWithRed:0.93 green:0.92 blue:0.91 alpha:1];
    [_collectionView registerClass:[LZHostDetailControllerViewCell class] forCellWithReuseIdentifier:@"hostIdentifier"];
    
    [_collectionView registerClass:[HeadViewButton class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headViewButton"];
    [self.contentView addSubview:_collectionView];
    
    self.progressView = [[MBProgressHUD alloc]initWithView:self.contentView];
    [[[_progressView subviews]firstObject] removeFromSuperview];
    [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
    [_progressView setMode:0];
    [_progressView show:YES];
    NSString  *name = @"RED.gif";
    _progressView.color = [UIColor clearColor];
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 10;
    imageView.opaque = NO;
    
    [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
    
    imageView.image = [UIImage sd_animatedGIFWithData:imageData];
    [[[_progressView subviews] lastObject] addSubview:imageView];
    [self.contentView addSubview:_progressView];
    
    _page = 1;
    [self getData];
    //下拉刷新
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataArray removeAllObjects];
        _page = 1;
        [self getData];
    }];
    //上拉加载
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getData];
    }];
    
}
- (void)getData{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_index?device=android&page=%ld", _page];
    [TwoToOne getDataByString:urlString BodyString:nil WithDataBlock:^(id data) {
        if ([[data objectForKey:@"list"]count] == 0) {
            [_collectionView.mj_footer endRefreshing];
            _collectionView.mj_footer.state = MJRefreshStateNoMoreData;
            return ;
        }
        _listArray = [data objectForKey:@"list"];
//        _array = [NSMutableArray arrayWithArray:_listArray];
        [_array addObjectsFromArray:_listArray];
        for (NSDictionary *dic in _listArray) {
            TheHost *theHost = [[TheHost alloc]init];
            [theHost setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:theHost];
            [_collectionView reloadData];
            
        }
        if (_page == 1) {
            
            if (_dataArray.count != 0) {
                NSDictionary *recommendBozhuDic = [data objectForKey:@"recommendBozhu"];
                NSArray *listTwoArray = [recommendBozhuDic objectForKey:@"list"];
                _zhuBoArray = [NSMutableArray arrayWithArray:listTwoArray];
                [_array insertObject:listTwoArray atIndex:1];
                TheHost *theHost1 = [[TheHost alloc]init];
                theHost1.title = @"新晋主播";
                theHost1.list = listTwoArray;
                [_dataArray insertObject:theHost1 atIndex:1];
            }
            [_collectionView reloadData];
        }
        [_progressView removeFromSuperview];
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    }];
   
}
#pragma mark - item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    TheHost *theHost = _dataArray[section];
    return theHost.list.count;
}
#pragma mark - cell的高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(115 * FITWidth, 185 * FITHeight);
}
#pragma mark - section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _dataArray.count;
}
#pragma mark - section的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.contentView.frame.size.width, 40 * FITHeight);
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    HeadViewButton *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headViewButton" forIndexPath:indexPath];
    
    [headView.leftButton setTitle:[_dataArray[indexPath.section] title] forState:UIControlStateNormal];
    
    headView.name = [_dataArray[indexPath.section] name];
    
    [headView.leftButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    
    headView.moreImageView.image = [UIImage imageNamed:@"更多"];
    [headView.moreButton setTitle:@"更多" forState:UIControlStateNormal];
    [headView.moreButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return headView;
    
}
#pragma mark - 更多点击方法
- (void)moreAction:(id)sender{
    BaseButton *button = sender;
    HeadViewButton *headView = (HeadViewButton *)button.superview;

    LZMoreViewController *lzmore = [[LZMoreViewController alloc]init];
    lzmore.nameString = headView.name;
    lzmore.zhuBoString = headView.leftButton.titleLabel.text;
    [self.LZTheHostnav pushViewController:lzmore animated:YES];
    
}
#pragma mark - cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LZHostDetailControllerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hostIdentifier" forIndexPath:indexPath];
    if (_dataArray.count == 0) {
        return cell;
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.dic = [[_dataArray[indexPath.section] list] objectAtIndex:indexPath.row];
    [cell.attentionButton addTarget:self action:@selector(attentionAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.attentionButton setTitle:@"关注" forState:UIControlStateNormal];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Dic"];
    NSArray *array = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for (Dic *s in array) {
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:s.dic];
        if ([[NSString stringWithFormat:@"%@", [dic objectForKey:@"uid"]] isEqualToString:[NSString stringWithFormat:@"%@", [[[_dataArray[indexPath.section] list] objectAtIndex:indexPath.row] objectForKey:@"uid"]]]) {
//            cell.attentionButton.titleLabel.text = @"已关注";
             [cell.attentionButton setTitle:@"已关注" forState:UIControlStateNormal];
            return cell;
        }
    }
    return cell;
}

#pragma mark - button点击事件
-(void)attentionAction:(id)sender{
    UIView *view = (UIView *)[sender superview];
    LZHostDetailControllerViewCell *cell = (LZHostDetailControllerViewCell *)view.superview;
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Dic"];
    NSArray *array = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    for (Dic *s in array) {
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:s.dic];
//        NSLog(@"%@", dic);
        if ([[NSString stringWithFormat:@"%@", [dic objectForKey:@"uid"]] isEqualToString:[NSString stringWithFormat:@"%@", [cell.dic objectForKey:@"uid"]]]) {
            [_manager.managedObjectContext deleteObject:s];
            cell.attentionButton.titleLabel.text = @"关注";
            [cell.attentionButton setTitle:@"关注" forState:UIControlStateNormal];
            [_manager saveContext];
            return;
        }
    }
    //添加
    Dic *dic = [NSEntityDescription insertNewObjectForEntityForName:@"Dic" inManagedObjectContext:_manager.managedObjectContext];
    dic.dic = [NSKeyedArchiver archivedDataWithRootObject:cell.dic];
//    NSLog(@"%@", cell.dic);
    cell.attentionButton.titleLabel.text = @"已关注";
    [cell.attentionButton setTitle:@"已关注" forState:UIControlStateNormal];
    [_manager saveContext];
}

#pragma mark - 点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    S1mpl3HeadInfoViewController *s1mpl3Head = [[S1mpl3HeadInfoViewController alloc]init];
    if (indexPath.section == 1) {
        s1mpl3Head.s1mpl3HeadDataSourceDic = _zhuBoArray[indexPath.row];
    }else{
//        NSLog(@"%ld", indexPath.section);
//        if (indexPath.section > 10 && indexPath.section < 20) {
//            s1mpl3Head.s1mpl3HeadDataSourceDic = [[_array[indexPath.section - 11] objectForKey:@"list"] objectAtIndex:indexPath.row];
//        }else if (indexPath.section > 20 && indexPath.section <= 29){
//            s1mpl3Head.s1mpl3HeadDataSourceDic = [[_array[indexPath.section - 21] objectForKey:@"list"] objectAtIndex:indexPath.row];
//        }else {
            s1mpl3Head.s1mpl3HeadDataSourceDic = [[_array[indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
//        }
    }
    [self.LZTheHostnav pushViewController:s1mpl3Head animated:YES];
    
}
- (void)layoutSubviews{
    [super layoutSubviews];
}
@end
